package com.aegean.socket.apacheMINA.main;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.log4j.Logger;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import com.aegean.socket.apacheMINA.handler.ClientMessageHandler;

public class Client {
	private static Logger log = Logger.getLogger(Client.class);
	private static final int port = 8080;
	private static final String host = "127.0.0.1";

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		init_Method();
	}

	private static boolean init_Method() {
		IoConnector conn = null;
		DefaultIoFilterChainBuilder filter = null;
		try {
			conn = new NioSocketConnector();
			conn.setConnectTimeoutMillis(30000);
			filter = conn.getFilterChain();
			filter.addFirst("logger", new LoggingFilter());
			filter.addLast("codec", new ProtocolCodecFilter(
					new TextLineCodecFactory(Charset.forName("UTF-8"),
							LineDelimiter.WINDOWS.getValue(),
							LineDelimiter.WINDOWS.getValue())));
			filter.addLast("stringserialize", new ProtocolCodecFilter(
					new ObjectSerializationCodecFactory()));
			conn.setHandler(new ClientMessageHandler());
			IoSession session = null;
			try {
				ConnectFuture future = conn.connect(new InetSocketAddress(host,
						port));
				future.awaitUninterruptibly(); // Wait until the connection
												// attempt is finished
				if (future.isConnected()) {
					session = future.getSession();
					InputStream reader = new BufferedInputStream(System.in);
					byte[] buffer = new byte[1024];
					while ((reader.read(buffer)) != -1) {
						session.write(buffer);
					}
					session.getCloseFuture().awaitUninterruptibly();
					conn.dispose();
				}else{
					log.info("没有发现服务器！");
				}
			} catch (ConnectException connE) {
				log.error("没有发现服务器的存在！");
			} catch (Exception e) {
				// TODO: handle exception

				log.error(e.getMessage(), e);
				if (session.isConnected())
					session.close(true);
				return false;
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			log.error(e.getMessage(), e);
			return false;
		}
		return true;
	}
}
